//
//  SettingList.m
//  Trading365
//
//  Created by yifei tong on 12-1-12.
//  Copyright (c) 2012年 dhc. All rights reserved.
//

#import "SettingList.h"
#import "Type.h"

@implementation SettingList
@synthesize table;
@synthesize Dict;
@synthesize arr,arrDescription;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

-(void)dealloc
{
    [table release];
    [Dict release];
    [arr release];
    [arrDescription release];
    [super dealloc];
}
#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    NSArray *array = [[NSArray alloc] initWithObjects: 
                      @"设置提醒",
                      @"标识",
                      @"声音",
                      @"震动",
                      nil];
    
    NSArray *arrayDes = [[NSArray alloc] initWithObjects: 
                         @"设置邮件是否后台提醒",
                         @"提示标识",
                         @"提示声音",
                         @"提示震动",
                         nil];
    
    
    self.arr = array;
    self.arrDescription = arrayDes;
    
    [self.view setBackgroundColor:BACKGROUND_COLOR];

    [array release];
    [arrayDes release];

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark -
#pragma mark Table Data Source Methods

-(NSString *)dataFilePath
{
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [path objectAtIndex:0];
    
    return [documentDirectory stringByAppendingPathComponent:KFileName];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [arr count];
}


- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
        return @"设置项";
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *ListCellIdentifier =
    @"ListCellIdentifier";
    
    UITableViewCell *cell = [tableView 
                             dequeueReusableCellWithIdentifier:ListCellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                       reuseIdentifier:ListCellIdentifier] 
                autorelease];
    }
    cell.contentView.backgroundColor = [UIColor clearColor];
    cell.backgroundColor = [UIColor clearColor];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    
    NSUInteger row = [indexPath row];
    
    // switch button
    UISwitch *aSwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
    [aSwitch addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
    
    NSString *filePath = [self dataFilePath];
    
    if([[NSFileManager defaultManager] fileExistsAtPath:filePath])
    {
        self.Dict = [[NSMutableDictionary alloc] initWithContentsOfFile:filePath];
    }    
    
    switch (row) {
        case 0:
            aSwitch.on = [[self.Dict valueForKey:Key_SetBackWarning] isEqualToString: @"True"] ? true : false;
            aSwitch.tag = 1;
            [cell addSubview:aSwitch];            
            cell.accessoryView = aSwitch;
            
            switchEnable = aSwitch.on;
            break;
        case 1:
            aSwitch.on = [[self.Dict valueForKey:Key_PersonalLetter] isEqualToString: @"True"] ? true : false;
            [cell addSubview:aSwitch];
            cell.accessoryView = aSwitch;
            aSwitch.enabled = switchEnable;
            break;
        case 2:
            aSwitch.on = [[self.Dict valueForKey:Key_LeaveMessage] isEqualToString: @"True"] ? true : false;
            [cell addSubview:aSwitch];
            cell.accessoryView = aSwitch;
            aSwitch.enabled = switchEnable ;
            break;
        case 3:
            aSwitch.on = [[self.Dict valueForKey:Key_Shake] isEqualToString: @"True"] ? true : false;
            
            [cell addSubview:aSwitch];
            cell.accessoryView = aSwitch;
            aSwitch.enabled = switchEnable;
            break;
        default:
            break;
    }
    
    cell.textLabel.text = [self.arr objectAtIndex:row];
    cell.detailTextLabel.text = [self.arrDescription objectAtIndex:row];
    //cell.accessoryType = UITableViewCellAccessoryCheckmark ;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

-(void)switchChanged:(id)sender
{
    
    UISwitch * switchControl = sender;
    UITableViewCell *switchSell = (UITableViewCell *)[switchControl superview];    
    
    NSInteger row = [[self.table indexPathForCell:switchSell] row];
    
    NSString *value = [[NSString alloc] initWithString: @"False"];
    
    if(switchControl.on)
    {
        [value release];
        value = @"True";
    }
    
    switch (row) {
        case 0:
            [self.Dict setValue:value forKey:Key_SetBackWarning];            
            [self setControlEnable:switchControl.on];
            break;
        case 1:
            [self.Dict setValue:value forKey:Key_PersonalLetter];
            break;
        case 2:
            [self.Dict setValue:value forKey:Key_LeaveMessage];
            break;
        case 3:
            [self.Dict setValue:value forKey:Key_Shake];
            [self vibrate];
            break;
        default:
            break;
    }
    
    [self settingSaves:self.Dict];
    
    [value release];   
}

-(void)setControlEnable:(BOOL) flag
{
    for(UITableViewCell * cellView in [self.table subviews])
    {
        for (UIView *view in cellView.subviews) 
        {
            if ([view isKindOfClass:[UISwitch class]]) 
            {
                UISwitch *eachSwitch = (UISwitch*)view;
                eachSwitch.enabled = eachSwitch.tag == 1 ? true : flag;
            }
        }
    }
}

-(void)settingSaves:(NSMutableDictionary *) dict
{
    [dict writeToFile:[self dataFilePath] atomically:YES];
}

- (void)vibrate
{
    AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
}



@end
